import sqlite3
import streamlit as st
import base64
import os


from duanwei import show_apex_visualization
from wuqi import show_weapon_statistics, WeaponStatistics
from datetime import datetime
from leg import show_legend_analysis

from zhanji import ApexAnalyzer


# 初始化数据库
def init_database():
    conn = sqlite3.connect('taobao.db')
    cursor = conn.cursor()

    # 创建用户表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT UNIQUE NOT NULL,
            password TEXT NOT NULL
        )
    ''')


    try:
        cursor.execute('INSERT INTO users (name, password) VALUES (?, ?)',
                       ('admin', 'password123'))
    except sqlite3.IntegrityError:
        pass  # 如果用户已存在，则忽略

    conn.commit()
    conn.close()


# 处理本地图片并设置为背景
def set_local_background(image_path):
    # 检查图片文件是否存在
    if not os.path.exists(image_path):
        st.error(f"背景图片不存在: {image_path}")
        return

    # 读取本地图片并进行Base64编码
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode()

    # 注入CSS样式，使用编码后的图片作为背景，并设置中文字体
    st.markdown(
        f"""
        <style>
        /* 设置中文字体 */
        html, body, [class*="css"] {{
            font-family: 'Microsoft YaHei', 'SimHei', 'STHeiti', sans-serif;
        }}

        .stApp {{
            background-image: url("data:image/jpeg;base64,{encoded_string}");
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            background-attachment: fixed;
        }}
        /* 可选：调整页面元素背景透明度，避免遮挡背景图 */
        .stBlockContainer {{
            background-color: rgba(255, 255, 255, 0.7);  /* 白色半透明背景 */
            padding: 2rem;
            border-radius: 10px;
        }}

        /* 特别设置标题和文本的中文字体 */
        h1, h2, h3, h4, h5, h6 {{
            font-family: 'Microsoft YaHei', 'SimHei', 'STHeiti', sans-serif;
        }}

        /* 设置侧边栏的中文字体 */
        .sidebar .sidebar-content {{
            font-family: 'Microsoft YaHei', 'SimHei', 'STHeiti', sans-serif;
        }}
        </style>
        """,
        unsafe_allow_html=True
    )


# 初始化数据库
init_database()

# 设置背景图片
set_local_background("C:/Users/27571/Desktop/机器视觉/aisaka-taiga/apex查询/back.jpg")

# 初始化会话状态
if 'page' not in st.session_state:
    st.session_state.page = 'login'
if 'registered_username' not in st.session_state:
    st.session_state.registered_username = ''
if 'logged_in' not in st.session_state:
    st.session_state.logged_in = False
if 'current_module' not in st.session_state:
    st.session_state.current_module = 'dashboard'
if 'current_user' not in st.session_state:
    st.session_state.current_user = ''


# 验证
def yanzheng(username, password):
    conn = sqlite3.connect('taobao.db')
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM users WHERE name = ? AND password = ?', (username, password))
    user = cursor.fetchone()
    conn.close()
    return user is not None


# 注册
def register_user(username, password):
    conn = sqlite3.connect('taobao.db')
    cursor = conn.cursor()
    try:
        cursor.execute('INSERT INTO users (name, password) VALUES (?, ?)', (username, password))
        conn.commit()
        return True
    except sqlite3.IntegrityError:
        return False
    finally:
        conn.close()





# 主页面模块
def show_dashboard():
    st.title("基地")
    st.write(f"欢迎回来，传奇{st.session_state.current_user}！")
    col1, col2, col3 = st.columns(3)

    with col1:
        st.metric("总玩家数", "4,632,871", "12%")
    with col2:
        st.metric("本月活跃", "2,156,432", "8%")
    with col3:
        st.metric("平均排名", "5.2", "-3%")

    st.subheader("快速导航")
    col1, col2 = st.columns(2)
    with col1:
        if st.button("查看排名分布", use_container_width=True):
            st.session_state.current_module = 'data_query'
            st.rerun()
    with col2:
        if st.button("武器数据管理", use_container_width=True):
            st.session_state.current_module = 'weapon_management'
            st.rerun()


def show_data_query():
    # 添加选择器让用户选择查看哪种数据
    option = st.selectbox(
        "选择要查看的数据类型",
        ["段位分布"],
        key="data_type_selector"
    )

    if option == "段位分布":
        show_apex_visualization()

def show_weapon_management():
    show_weapon_statistics()


def LEGS():
    show_legend_analysis()

def zhanjigl():

    a=ApexAnalyzer()
    a.run()




# 主页面框架
def show_main_page():
    # 侧边栏导航
    with st.sidebar:
        st.title("APEX查询系统")
        st.markdown("---")

        # 导航选项
        if st.button(" 主页", use_container_width=True):
            st.session_state.current_module = 'dashboard'
            st.rerun()

        if st.button("数据查询", use_container_width=True):
            st.session_state.current_module = 'data_query'
            st.rerun()

        if st.button(" 武器管理", use_container_width=True):
            st.session_state.current_module = 'weapon_management'
            st.rerun()

        if st.button(" 英雄选取率", use_container_width=True):
            st.session_state.current_module = 'LegendAnalysis'
            st.rerun()

        if st.button("战绩", use_container_width=True):
            st.session_state.current_module = 'zhanjigl'
            st.rerun()

        st.markdown("---")
        if st.button("🚪 退出登录", use_container_width=True):
            st.session_state.logged_in = False
            st.session_state.page = 'login'
            st.session_state.current_user = ''
            st.rerun()


    if st.session_state.current_module == 'dashboard':
        show_dashboard()
    elif st.session_state.current_module == 'data_query':
        show_data_query()
    elif st.session_state.current_module == 'weapon_management':
        show_weapon_management()
    elif st.session_state.current_module == 'LegendAnalysis':
        LEGS()
    elif st.session_state.current_module == 'zhanjigl':
        zhanjigl()



if st.session_state.page == 'login':
    st.markdown(
        "<h1 style='color: white; text-shadow: 2px 2px 5px black; font-family: Microsoft YaHei, SimHei, STHeiti, sans-serif;'>登录页面</h1>",
        unsafe_allow_html=True)


    if st.session_state.registered_username:
        st.success(f"账号 {st.session_state.registered_username} 创建成功！请登录")
        st.session_state.registered_username = ''  # 重置


    username = st.text_input("请输入用户名", key="login_username")
    password = st.text_input("请输入密码", type="password", key="login_password")

    if st.button("登录"):
        if not username or not password:
            st.error("请填写所有字段！")
        elif len(password) < 6:
            st.error("密码长度不能少于6位！")
        else:
            if yanzheng(username, password):
                st.success("欢迎回来，传奇")
                st.session_state.logged_in = True
                st.session_state.page = 'main'
                st.session_state.current_user = username
                st.rerun()
            else:
                st.error("登录失败！用户名或密码错误。")

    st.markdown("---")
    if st.button("点击创建账号"):
        st.session_state.page = 'register'
        st.rerun()

elif st.session_state.page == 'register':

    st.markdown(
        "<h1 style='color: white; text-shadow: 2px 2px 5px black; font-family: Microsoft YaHei, SimHei, STHeiti, sans-serif;'>创建账号</h1>",
        unsafe_allow_html=True)


    username2 = st.text_input("请输入用户名", key="register_username")
    password2 = st.text_input("请输入密码", type="password", key="register_password")
    password3 = st.text_input("请确认密码", type="password", key="register_confirm_password")

    col1, col2 = st.columns(2)

    with col1:
        if st.button("注册"):
            if not username2 or not password2:
                st.error("请填写所有字段！")
            elif len(password2) < 6:
                st.error("密码长度不能少于6位！")
            elif password2 != password3:
                st.error("两次输入的密码不一致！")
            else:
                if register_user(username2, password2):
                    st.session_state.registered_username = username2
                    st.session_state.page = 'login'
                    st.rerun()
                else:
                    st.error("用户名已存在！")

    with col2:
        if st.button("返回登录"):
            st.session_state.page = 'login'
            st.rerun()

elif st.session_state.page == 'main' and st.session_state.logged_in:
    # 主页面
    show_main_page()